import mqtt from 'precompiled-mqtt'
import { mainStore, chartStore } from '@/store/index.js';
const store = mainStore();
const storeChart = chartStore();
import { throttle } from 'lodash';
import logHandler from '@/utils/logHandler.js'
const { ipcRenderer } = require('electron');


import { ElMessage } from 'element-plus';
class MqttClient {
    constructor() {
        this.client = null;
        this.total = 0
        this.heard = null
        this.clientId = null
    }

    connect() {
        this.clientId = "mqttjs_" + Math.random().toString(16).substr(2, 8);
        this.client = mqtt.connect(store.ConfigJsInfo.mqttUrl.wsMqtt_bj, {
            clean: false,// 连接建立时是否清除之前的会话信息
            username: store.username,
            password: store.password,
            clientId: this.clientId,
            keepalive: 60,
            reconnectPeriod: 5000,// 重连间隔
        });
        this.client.on('connect', () => {
            window.clearInterval(this.heard)
            this.heard = window.setInterval(() => {
                this.client.publish("weituo", '50;', { qos: 2 });
            }, 30000);
            this.client.subscribe("hangqing/+", { qos: 2 }, (error) => {
                if (error) {
                    ElMessage({ message: "订阅失败，按F5刷新重试", type: 'error' });
                }
            });
        });
        this.client.on('message', throttle(async (topic, message) => {
            let msg = message.toString()
            if (msg.startsWith("fenshi")) {
                storeChart.setFenshiData(msg)
            } else if (msg.startsWith("k_")) {
                storeChart.setKlineData(msg)
            } else if (msg.startsWith(store.selectHeyue.heyue_bh)) {
                storeChart.setlastKLineData(msg)
            } else {
                storeChart.setHagnqingData(msg)
            }
        }, 0));
        this.client.on("reconnect", () => {
            this.total++;
            if (this.total >= 5) {
                this.disconnect()
            }
        });
        this.client.on("error", () => {
            this.total++;
            if (this.total >= 5) {
                this.disconnect()
                logHandler.writeLog(`系统`, `行情链接意外断线`)
                ipcRenderer.send('set-networkdetail-log', '行情链接意外断线')
                // return ElMessage({ message: "链接断开，按F5刷新后重新开始", type: 'error' });
                return alert('链接断开，按F5刷新后重新开始')
            }
            this.connect()
        });
        this.client.on("close", () => {
            this.disconnect()
            let num = localStorage.getItem('runclose') || 0
            num++
            localStorage.setItem('runclose', num)
            ipcRenderer.send('set-networkdetail-log', '行情链接关闭')
            logHandler.writeLog(`系统`, `行情链接关闭`)
            // ElMessage({ message: "链接断开，按F5刷新后重新开始", type: 'error' });
            alert('链接断开，按F5刷新后重新开始')
        });
    }

    // 订阅指定主题
    subscribe(topic) {
        if (topic == 'hangqing/+') {
            this.unsubscribe(topic)
        }
        this.client.subscribe(topic, { qos: 2 });
    }

    // 取消订阅指定主题
    unsubscribe(topic) {
        this.client.unsubscribe(topic, { qos: 2 });
    }

    // 发布消息
    publish(message) {
        this.client.publish("kxian/weituo", message, { qos: 0 });
    }

    // 断开连接
    disconnect() {
        window.clearInterval(this.heard)
        if (this.client) {
            this.client.end();
            this.client = null
        }
    }
}
export default MqttClient;
